<template>
  <a-drawer
      v-model:open="open"
      class="custom-class"
      :width="640"
      root-class-name="root-class-name"
      :keyboard="false"
      :maskClosable="false"
      title="角色授权菜单列表"
      placement="right"
      :closable="false"
  >
    <template #extra>
      <a-button style="margin-right: 8px" @click="handleClose"><close-outlined></close-outlined>关闭</a-button>
      <a-button type="primary" @click="handleSubmit"><check-outlined></check-outlined>保存</a-button>
    </template>
    <a-tree
        v-model:expandedKeys="expandedKeys"
        v-model:selectedKeys="selectedKeys"
        v-model:checkedKeys="checkedKeys"
        :field-names="fieldNames"
        checkable
        checkStrictly
        :multiple="true"
        :blockNode="true"
        :autoExpandParent="true"
        :tree-data="treeData"
    >
      <template #title="{ title, key }">
        <span>{{ title }}</span>
      </template>
    </a-tree>
  </a-drawer>
</template>
<script setup>
const open = ref(false)
const treeData = ref([])
const expandedKeys = ref([]);
const selectedKeys = ref([]);
const checkedKeys = ref([]);
const currentRoleId = ref("")
const fieldNames = {
  key:'id'
};

watch(expandedKeys, () => {
  console.log('expandedKeys', expandedKeys);
});
watch(selectedKeys, () => {
  console.log('selectedKeys', selectedKeys);
});
watch(checkedKeys, () => {
  console.log('checkedKeys', checkedKeys);
});

const handleLoadMenuData = async (roleId)=>{
    const resp = await userLoadMenuApi({})
    treeData.value = resp.data;
    expandedKeys.value = handleGetAllKeys(resp.data)
    // 查询当前角色对应的权限信息，并选中回填即可
    const resp2 = await useRoleMenusApi(roleId)
    checkedKeys.value = { "checked": handleGetAllKeys(resp2.data), "halfChecked": [] }
}

// 保存角色权限
const  handleSubmit = async() => {
  try {
    if(checkedKeys.value && checkedKeys.value.length == 0){
      useMessage().error("请选中一个菜单项进行操作")
      return;
    }
    await useBindMenusRoleDataApi({roleId:currentRoleId.value,menusIds:checkedKeys.value.checked})
    useMessage().success("授权成功")
    handleClose()
  }catch (e){
    useMessage().error(e.msg || "授权失败")
  }

}


const handleGetAllKeys = (dataArr)=>{
  var arr = []
  callback(dataArr)
  function callback(arrdata){
    arrdata.forEach(c=>{
      arr.push(c.id)
      if(c.children && c.children.length > 0) {
        callback(c.children)
      }
    })
  }
  return arr
}
const handleOpen = (roleId)=>{
  open.value = true;
  currentRoleId.value = roleId
  handleLoadMenuData(roleId)
}

const handleClose = ()=>{
  checkedKeys.value = []
  selectedKeys.value = []
  expandedKeys.value = []
  open.value = false;
}

defineExpose(({
  handleOpen
}))

</script>